package com.tingyuge.thinking.spring.configuration.bean.lifecycle;

import com.tingyuge.thinking.spring.ioc.overview.domain.SuperUser;
import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * bean 实例化 生命周期实例
 *
 * @author xiaodao
 * @version 1.0
 * @date 2021/7/10
 */
public class BeanInstantiationLifecycleDemo {
    public static void main(String[] args) {
      executeBeanFactory();
        System.out.println("-----------------------------------");
      executeApplicationContext();
    }
    public static  void executeBeanFactory(){
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        //方法1: 添加 beanPostProcessor 实例 MyInstantiationAwareBeanPostProcessor
//        beanFactory.addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());
        //方法二: 将 MyInstantiationAwareBeanPostProcessor 作为一个bean添加进去
        //基于 XML 资源 BeanDefinitionReader
        String[] locations = {"/META-INF/dependency-lookup-context.xml", "/META-INF/bean-dependency-construct-injection.xml"};
        //指定字符编码
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
        int beforeDefinition = beanFactory.getBeanDefinitionCount();
        int afterBeanDefinition = xmlBeanDefinitionReader.loadBeanDefinitions(locations);
        int beanDefinitionCount = afterBeanDefinition - beforeDefinition;
        System.out.println("已加载: BeanDefinition的数量: " + beanDefinitionCount);
        SuperUser supperUser = beanFactory.getBean("superUser", SuperUser.class);
        System.out.println(supperUser);
        User user = beanFactory.getBean("user", User.class);
        System.out.println(user);
        //按照类型的方式进行注入  resolveDependency
        UserHolder userHolder = beanFactory.getBean("userHolder", UserHolder.class);
        System.out.println(userHolder);
    }

    public static  void executeApplicationContext(){
        ClassPathXmlApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext();

        //添加 beanPostProcessor 实例 MyInstantiationAwareBeanPostProcessor

        //基于 XML 资源 BeanDefinitionReader
        String[] locations = {"/META-INF/dependency-lookup-context.xml", "/META-INF/bean-dependency-construct-injection.xml"};
        xmlApplicationContext.setConfigLocations(locations);
        xmlApplicationContext.refresh();
        User user = xmlApplicationContext.getBean("user", User.class);
        System.out.println(user);
        //按照类型的方式进行注入  resolveDependency
        UserHolder userHolder = xmlApplicationContext.getBean("userHolder", UserHolder.class);
        System.out.println(userHolder);
        xmlApplicationContext.getBeanFactory().preInstantiateSingletons();
        xmlApplicationContext.close();


    }


}
